package org.dormi.learn.completablefuture;

import java.util.concurrent.*;

/**
 * then combine操作
 * 场景:
 * - 异步获取价格1 - step1
 * - 异步获取价格2 - step2
 * - 计算平均值 (其中 step1, step2 无关)
 *
 * @author : dormi330
 * @since : 22/04/18
 */
public class CompletableFutureDemo06 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("x1 " + Thread.currentThread().getName());
            timeConsuming(3000);
            return 30;
        }, executorService)
            .thenCombine(
                // 第一个参数 CompletableFuture<V>
                CompletableFuture.supplyAsync(() -> {
                    System.out.println("x2 " + Thread.currentThread().getName());
                    timeConsuming(3000);
                    return 50;
                }, executorService),
                // 参数2: 2个输出的处理
                (p1, p2) -> {
                    return (p1 + p2) / 2;
                }
            );

        try {
            Integer result = future.get(5, TimeUnit.SECONDS);
            System.out.println("result= " + result);//result=1
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        executorService.shutdown();
    }
    /*
x1 pool-1-thread-1
x2 pool-1-thread-2
result= 40
    */
    /** 模拟耗时处理 */
    private static void timeConsuming(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
